package com.haoxuer.discover.qrcode.view;

import net.glxn.qrgen.core.image.ImageType;
import net.glxn.qrgen.javase.QRCode;
import org.springframework.web.servlet.view.AbstractView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class QRView extends AbstractView {
  @Override
  protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
    setContentType("image/jpeg");
    String code = model.get("code") + "";
    int width = getModel(model, "width", 300);
    int height = getModel(model, "height", 300);
    ServletOutputStream out = response.getOutputStream();
    QRCode.from(code).withCharset("UTF-8").to(ImageType.JPG).withSize(width, height).writeTo(out);
    out.flush();
  }

  private Integer getModel(Map<String, Object> model, String key, int defaultValue) {
    Integer result = (Integer) model.get(key);
    if (result == null) {
      result = defaultValue;
    }

    return result;
  }
}
